import * as THREE from 'three'
import { Float32BufferAttribute } from 'three'
import createApp from '../../core'

function createSnowflakes (dom: HTMLElement) {
  const { camera, scene, update } = createApp(dom)
  scene.background = new THREE.Color(0xdddddd)
  camera.position.set(-150, 100, 120)
  camera.lookAt(scene.position)

  //   const axes = new THREE.AxesHelper(100)
  //   scene.add(axes)

  createTextures().then(textures => {
    textures.forEach((texture) => {
      const geometry = new THREE.BufferGeometry()
      const material = new THREE.PointsMaterial({
        size: 3,
        map: texture,
        transparent: true,
        // 解决图像黑框问题
        depthWrite: false,
        blending: THREE.AdditiveBlending
        // alphaTest: 0.1,
        // blending: THREE.CustomBlending,
        // blendSrc: THREE.SrcColorFactor,
        // blendDst: THREE.DstAlphaFactor,
        // blendEquation: THREE.AddEquation
      })
      material.color.setHSL(0.5, 0.2, 0.3)
      const vectors = []
      for (let index = 0; index < 60000; index++) {
        vectors.push(createNumber(1000), createNumber(1000), createNumber(1000))
      }
      geometry.setAttribute('position', new Float32BufferAttribute(vectors, 3))
      const mesh = new THREE.Points(geometry, material)
      //   mesh.rotation.x = Math.random() * 6
      //   mesh.rotation.y = Math.random() * 6
      //   mesh.rotation.z = Math.random() * 6
      scene.add(mesh)
    })
  })

  const speeds = [0.1, 0.2, 0.3, 0.4, 0.5]
  update(() => {
    // console.log(time)
    scene.children.forEach((child, i) => {
      const mesh = child as THREE.Points
      const positions = mesh.geometry.getAttribute('position')
      for (let index = 0; index < positions.count; index++) {
        let y = positions.getY(index)
        y -= speeds[i]

        if (y < -500) y = 500

        positions.setY(index, y)
      }
      positions.needsUpdate = true
    })
  })
}

const loader = new THREE.TextureLoader()
async function createTextures (): Promise<THREE.Texture[]> {
  const imgs = await Promise.all([
    import('@/assets/sprites/snowflake1.png'),
    import('@/assets/sprites/snowflake2.png'),
    import('@/assets/sprites/snowflake3.png'),
    import('@/assets/sprites/snowflake4.png'),
    import('@/assets/sprites/snowflake5.png')
  ])
  return imgs.map(img => loader.load(img.default))
}

function createNumber (num: number) {
  return Math.random() * num - num / 2
}

export {
  createSnowflakes
}
